package com.rerun.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.rerun.entity.vo.JobDetailVo;
import com.rerun.entity.vo.JobMessageVo;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.ibatis.annotations.Param;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestParam;

import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.rerun.common.bean.Rest;
import com.rerun.entity.Job;
import com.rerun.entity.JobTag;
import com.rerun.entity.JobTagJob;
import com.rerun.entity.YoyoPark;
import com.rerun.enums.JobStateEnum;
import com.rerun.mapper.JobMapper;
import com.rerun.mapper.JobTagJobMapper;
import com.rerun.mapper.JobTagMapper;
import com.rerun.mapper.YoyoParkMapper;
import com.rerun.service.IJobService;
import com.rerun.vo.park.JobValidVo;

import java.lang.reflect.InvocationTargetException;
import java.util.*;

/**
 * The type Job service.
 *
 * @author Administrator 发布职位
 */
@Service
public class JobServiceImpl extends ServiceImpl<JobMapper, Job> implements IJobService {
    /**
     * The constant logger.
     */
    public static final Logger logger = Logger.getLogger(JobServiceImpl.class);
    @Autowired
    private JobMapper jobMapper;
    @Autowired
    private JobTagJobMapper jobTagJobMapper;
    @Autowired
    private JobTagMapper jobTagMapper;
    @Autowired
    private YoyoParkMapper yoyoParkMapper;

    @Override
    public Rest addJob(Job job) {

        job.setCreateTime(new Date());
        job.setUpdateTime(new Date());
        job.setStatus(Integer.parseInt(JobStateEnum.normal.getKey()));
        // 职位状态 0正常1发布(待审核)2审核失败4停止招聘
        try {

            jobMapper.insert(job);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("职位发布失败具体原因" + e.getMessage());
        }
        return Rest.okData(job);
    }

    // 更新
    @Override
    public Rest updateJob(Job job) {
        job.setCreateTime(new Date());
        job.setUpdateTime(new Date());
        job.setStatus(Integer.parseInt(JobStateEnum.release.getKey()));
        jobMapper.updateById(job);
        return Rest.ok("信息更新成功");
    }

    // 已发职位展示
    @Override
    public Rest showJob(Long parkid) {

        Map<String, Object> columnMap = new HashMap<>();
        columnMap.put("parkId", parkid);
        List<Job> map = jobMapper.selectByMap(columnMap);
        return Rest.okData(map);
    }

    @Override
    public Page<Job> findNewJobs(Page<Job> page) {
        List<Job> jobs = jobMapper.findNewJobs(page);
        page.setRecords(jobs);
        return page;
    }

    @Override
    public Page<Job> findPageByWorkDistrict(Page<Job> page,String workCity, String workDistrict, String keyWord,String edu, String salaryRange,  String workYears) {
        List<Job> jobs = jobMapper.findPageByWorkDistrict(page,workCity, workDistrict, keyWord,edu,salaryRange,workYears);
        page.setRecords(jobs);
        return page;
    }

    @Override
    public boolean addJob(Job job, List<JobTag> jobTags) {
        Date now = new Date();
        job.setCreateTime(now);
        job.setUpdateTime(now);
        jobMapper.insert(job);
        String jobId = job.getId();

        if (jobTags != null && jobTags.size() > 0) {
            for (JobTag jobTag : jobTags) {
                JobTagJob jobTagJob = new JobTagJob();
                jobTagJob.setJobId(jobId);
                jobTagJob.setJobtagId(jobTag.getId());

                jobTagJobMapper.insert(jobTagJob);
            }
        }

        return true;
    }

    @Override
    public boolean editJob(Job job, List<JobTag> jobTags) {
        Date now = new Date();
        job.setUpdateTime(now);
        jobMapper.updateById(job);
        String jobId = job.getId();

        //删除关联
        EntityWrapper<JobTagJob> wrapper = new EntityWrapper<>();
        wrapper.where("jobId={0}", jobId);
        jobTagJobMapper.delete(wrapper);

        //添加关联
        if (jobTags != null && jobTags.size() > 0) {
            for (JobTag jobTag : jobTags) {
                JobTagJob jobTagJob = new JobTagJob();
                jobTagJob.setJobId(jobId);
                jobTagJob.setJobtagId(jobTag.getId());

                jobTagJobMapper.insert(jobTagJob);
            }
        }
        return true;
    }

    @Override
    public List<Job> findAvailableJobByParkId(String parkId) {
        return jobMapper.findAvailableJobByParkId(parkId);
    }

    @Override
    public JobValidVo getJobDetail(String id) {
        JobValidVo jobValidVo = new JobValidVo();
        Job job = jobMapper.selectById(id);

        if (job == null) return null;

        try {
            BeanUtils.copyProperties(jobValidVo, job);
        } catch (IllegalAccessException | InvocationTargetException e) {
            e.printStackTrace();
            logger.info("bean拷贝异常", e);
            return jobValidVo;
        }

        EntityWrapper<JobTagJob> wrapper = new EntityWrapper<>();
        wrapper.where("jobId={0}", id);
        List<JobTagJob> jobTagJobs = jobTagJobMapper.selectList(wrapper);
        List<JobTag> jobTags = new ArrayList<>();
        if (jobTagJobs != null && jobTagJobs.size() > 0) {
            for (JobTagJob jobTagJob : jobTagJobs) {
                jobTags.add(jobTagMapper.selectById(jobTagJob.getJobtagId()));
            }
        }
        jobValidVo.setJobTags(jobTags);
        return jobValidVo;
    }

    @Override
    public Page<Job> findPageByIntention(Page<Job> page, String memberId) {
        List<Job> jobs = jobMapper.findPageByIntention(page, memberId);
        page.setRecords(jobs);
        return page;
    }

	@Override
	public JobDetailVo getJobDetailAndYoyoPark(String id) {
		return jobMapper.jobDetail(id);
	}

    @Override
    public Job findAvailableJobById(String jobId) {
        return jobMapper.findAvailableJobById(jobId);
    }

    @Override
    public List<JobDetailVo> jobDetails(List<String> ids) {
        return jobMapper.jobDetails(ids);
    }

    @Override
    public JobDetailVo getJobDetailById(String jobId) {
        return jobMapper.getJobDetailById(jobId);
    }

    
    /**
     * 后台职位管理列表
     */
	@Override
	public List<JobMessageVo> showjobMessage(@Param("map") Map<String, Object >  map,@PathVariable("pageNumber") Integer pageNumber, 
    		@RequestParam(defaultValue = "15") Integer pageSize) throws Exception{
		
		return   jobMapper.showjobMessage(map);
	}
	
	/**
     *  后台职位管理列表编辑查询回显
     */
    public JobMessageVo findjobMessage(@Param("id")String id){
    	
    	return jobMapper.findjobMessage(id);
    }

   /**
    * 后台职位管理列表编辑
    * 
    */
     public Rest updateJobMessage(JobMessageVo JobMessage){
    	 String id = JobMessage.getId();
    	 String jobName = JobMessage.getJobName();
    	 String workYears = JobMessage.getWorkYears();
    	 String edu = JobMessage.getEdu();
    	 String salaryRange = JobMessage.getSalaryRange();
    	 long status = JobMessage.getStatus();
    	 String needSkills = JobMessage.getNeedSkills();
    	 String updateMan = JobMessage.getUpdateMan();
    	 
    	 
    	 try {
    		 EntityWrapper<Job> wraaper=new EntityWrapper<Job>();
        	 wraaper.eq("id", id);
        	 Job Job = jobMapper.selectById(id);
        	 long parkId = Job.getParkId();
        	 if(parkId!=0){
        		 Job.setJobName(jobName);
            	 Job.setWorkYears(workYears);
            	 Job.setEdu(edu);
            	 Job.setSalaryRange(salaryRange);
            	 Job.setStatus(status);
            	 Job.setNeedSkills(needSkills);
            	 Job.setUpdateTime(new Date());
            	 Job.setUpdateMan(updateMan);
            	 Job.setJobType(jobName);
            	 jobMapper.update(Job, wraaper);
        	  
        	 }
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			 return Rest.failure("该园所已不存在");
		}
    	
    	 return Rest.ok();
    }
}
